﻿var map, geoLocationProvider, gpsLayer, trafficLayer;

function GetMap() {
    var mapOptions =
    {
        credentials: "YOUR_BING_MAPS_KEY",
        zoom: 2
    };

    map = new Microsoft.Maps.Map(document.getElementById("myMap"), mapOptions);
    
    gpsLayer = new Microsoft.Maps.EntityCollection();
    map.entities.push(gpsLayer);
}

function ToggleGPS(args) {

    // Initialize the location provider
    if (!geoLocationProvider) {
        geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);
    }

    //Clear the GPS layer 
    gpsLayer.clear();

    if (args.checked) {
        // Get the user's current location
        geoLocationProvider.getCurrentPosition({
            successCallback: function (e) {
                gpsLayer.push(new Microsoft.Maps.Pushpin(e.center));
            }
        });
    } else {
        //Remove the accuracy circle and cancel any request that might be processing
        geoLocationProvider.removeAccuracyCircle();
        geoLocationProvider.cancelCurrentRequest();
    }
}

function ToggleTraffic() {
    //Check to see if the traffic layer exists
    if (trafficLayer) {
        //Get a reference to the traffic checkbox
        var chbx = document.getElementById('TrafficChbx');

        //Hide or Show the tile layer based on checked state
        if (chbx.checked) {
            trafficLayer.show();
        } else {
            trafficLayer.hide();
        }
    } else {
        //Load the traffic module and create the traffic layer.
        Microsoft.Maps.loadModule('Microsoft.Maps.Traffic', {
            callback: function () {
                //Create the traffic layer
                trafficLayer = new Microsoft.Maps.Traffic.TrafficLayer(map);

                //Get the base tile layer and set the opacity
                var layer = trafficLayer.getTileLayer();
                layer.setOptions({ opacity : 0.5 });

                //Toggle the traffic layer to the current state of the checkbox.
                ToggleTraffic();
            }});
    }
}

//Initialization logic for loading the map control
(function () {
    function initialize() {
        Microsoft.Maps.loadModule('Microsoft.Maps.Map', { callback: GetMap });
    }

    document.addEventListener("DOMContentLoaded", initialize, false);
})();